#include "stdafx.h"
#include "Manager.h"
#include <utility/Streams.h>
#include <log4cplus/configurator.h>

#ifdef WIN32
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif //_DEBUG
#endif //WIND32

namespace serika
{
	namespace log
	{
		Manager::Manager()
		{
		}

		Manager::~Manager()
		{
		}

		// static
		Manager& Manager::Singleton()
		{
			static Manager singleton;
			return singleton;
		}

		// static 
		void Manager::Init(const ut::String& config)
		{
			Manager::Singleton()._Init(config);
		}

		inline void Manager::_Init(const ut::String& config)
		{
			log4cplus::PropertyConfigurator::doConfigure(config);
		}

		// static
		log4cplus::Logger& Manager::GetLogger(const ut::String& name)
		{
			if (name.empty() || ut::String(_T("root")) == name)
			{
				return Manager::Singleton()._GetRootLogger();
			}
			else
			{
				return Manager::Singleton()._GetLogger(name);
			}
		}

		inline log4cplus::Logger& Manager::_GetLogger(const ut::String& name)
		{
			LoggerMap::iterator iter = mLoggerMap.find(name);
			if (mLoggerMap.end() != iter)
			{
				return iter->second;
			}

			//mLoggerMap[name] = log4cplus::Logger::getInstance(name);
			const log4cplus::Logger& logger = log4cplus::Logger::getInstance(name);
			iter = mLoggerMap.insert(std::make_pair(name, logger)).first;
			return iter->second;
			//return mLoggerMap[name];
		}

		inline log4cplus::Logger& Manager::_GetRootLogger()
		{
			ut::String rootName = _T("root");
			LoggerMap::iterator iter = mLoggerMap.find(rootName);
			if (mLoggerMap.end() != iter)
			{
				return iter->second;
			}

			const log4cplus::Logger& logger = log4cplus::Logger::getInstance(rootName);
			iter = mLoggerMap.insert(std::make_pair(rootName, logger)).first;
			return iter->second;
			//mLoggerMap[rootName] = log4cplus::Logger::getRoot();
			//return mLoggerMap[rootName];
		}
	}
}
